import threading
# shared_state.py


"""
共享数据模块，用于解决循环引用问题
"""
import threading

from collections import deque, defaultdict

# 限制数据点数量
MAX_DATA_POINTS = 1000
# 线程锁，用于保护共享数据的访问
data_lock = threading.Lock()



# 创建一个自定义的字典类，自动为新键创建有限大小的deque
class LimitedDataDict(dict):
    def __missing__(self, key):
        # 当访问不存在的键时，自动创建一个有限大小的deque
        # with data_lock:
        if key not in self:
            self[key] = deque(maxlen=MAX_DATA_POINTS)
        return self[key]
    
    def append_data(self, key, value):
        """向指定键添加数据"""
        # with data_lock:
        if key not in self:
            self[key] = deque(maxlen=MAX_DATA_POINTS)
        self[key].append(value)
    
    def get_latest(self, key, count=100):
        """获取指定键的最新数据"""
        if key not in self:
            return []

        # with data_lock:
        if key in self and len(self[key]) > 0:
            return list(self[key])[-count:]
        return []

# 使用自定义字典
torque_data = LimitedDataDict()

# 初始化基本的转向数据字段
torque_data['steering_angle'] = deque(maxlen=MAX_DATA_POINTS)
torque_data['steering_rate'] = deque(maxlen=MAX_DATA_POINTS)
torque_data['rate_dir'] = deque(maxlen=MAX_DATA_POINTS)

# 全局变量
G_ROLL_CNT = 0
G_READY_ROLL_CNT = 0
G_RATE_DIR = 1
G_STEERING_RATE = 0.0
G_STEERING_WHEEL_ANGLE = 0.0
G_STEERING_WHEEL_ANGLE_OLD = 0.0
G_THROTTLE = 0.0
G_BRAKE = 0.0
G_HAND_FORCE = 0.0

# CAN ID
G_STEERING_CAN_ID = 0x11F
G_STEERING_SBW_CAN_ID = 0x8E
# G_STEERING_SBW_CAN_ID = 0x11F
G_THROTTLE_BRAKE_CAN_ID = 0x342

# 运行标志事件
run_main_flag_event = threading.Event()
global_lock = threading.Lock()
